from django_smtpd import resolvers
from django_smtpd import client
import logging

class BasicMessageHandler(object):

  def process_message(self, message):
    logging.debug("processing message from %s" % self)
    resp = self.get_response(message)
    if isinstance(resp, list):
      client.default_connection().send_messages(resp)
    elif resp:
      resp.send()
      

  def __repr__(self):
    return self.__class__.__name__

  def get_response(self, message):
    from django.conf import settings
    mailconf = getattr(message, "mailconf", settings.ROOT_MAILCONF)
    resolver = resolvers.RegexMailResolver(r'', mailconf)

    try:
      callback, callback_args, callback_kwargs = resolver.resolve(message)

      #todo: mail middleware

      try:
        response = callback(message, *callback_args, **callback_kwargs)
      except Exception, e:
        #todo: exception midldleware
        raise
      return response
    except:
      raise
#    except RecipientNotFound, e:
#            return
#            if settings.DEBUG and false:
#                #todo : reply with technical response
#                return debug.technical_404_response(request, e)
#            else:
#                try:
#                    callback, param_dict = resolver.resolve404()
#                    return callback(request, **param_dict)
#                except:
#                    try:
#                        return self.handle_uncaught_exception(request, resolver, sys.exc_info())
#                    finally:
#                        receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
#    except exceptions.PermissionDenied:
#            return http.HttpResponseForbidden('<h1>Permission denied</h1>')
#    except SystemExit:
#            # Allow sys.exit() to actually exit. See tickets #1023 and #4701
#            raise
#    except: # Handle everything else, including SuspiciousOperation, etc.
#            # Get the exception info now, in case another exception is thrown later.
#            exc_info = sys.exc_info()
#            receivers = signals.got_request_exception.send(sender=self.__class__, request=request)
#            return self.handle_uncaught_exception(request, resolver, exc_info)
